﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using HPCERP.Infrastructure.RepositoryFramework.Configuration;
using HPCERP.Infrastructure.DomainBase;

namespace HPCERP.Infrastructure.RepositoryFramework
{
    public static class RepositoryFactory
    {
        private static Dictionary<string, object> repositories = new Dictionary<string, object>();

        public static TRepository GetRepository<TRepository, TEntity>()
            where TRepository : class, IRepository<TEntity>
            where TEntity : EntityBase
        {
            // Initialize the provider´s default value
            TRepository repository = default(TRepository);

            string interfaceShortName = typeof(TRepository).Name;
            if(!RepositoryFactory.repositories.ContainsKey(interfaceShortName))
            {
                // Not there, so create it
                // Get the repositoryMappingConfiguration config section
                RepositorySettings settings = (RepositorySettings) ConfigurationManager.GetSection(RepositoryMappingConstants.RepositoryMappingsConfigurationSectionName);
                repository = Activator.CreateInstance(Type.GetType(settings.RepositoryMappings[interfaceShortName].RepositoryFullTypeName)) as TRepository;
                    
                // Add the new provider instance to the cache
                RepositoryFactory.repositories.Add(interfaceShortName,repository);
            } else {
                // The provider was in the cache, so retrieve it
                repository = (TRepository)RepositoryFactory.repositories[interfaceShortName];
            }
            return repository;
        }
    }
}
